import store from '../store/index'
import { appId, wAppId } from '../plugins';
const http = {
    request(option = {}) {
        const {url, data, method = 'get', header={'content-type': 'application/json'}, useToken = true} = option;
        if(useToken) {
            header['Cookie'] = '_java110_token_=' + store.state.token;
        }
        header['app-id'] = wAppId;
        header['w-app-id'] = appId;
        header['transaction-id'] = new Date().getTime();
        header['req-time'] = '20230404144039';
        return new Promise((resolve, reject) => {
            wx.request({
                url: url,
                data: data,
                header: header,
                method: method,
                timeout: 20000,
                success: res => {
                    if(res.data.meta && res.data.meta.code == 1996) {
                        // store.dispatch("clearStates");
                        // wx.showModal({
                        //     title: "提示",
                        //     content: "登录已过期",
                        //     showCancel: true,
                        //     cancelText: "取消",
                        //     confirmText: "前往登录",
                        //     success: res => {
                        //         if(res.confirm) {
                        //             wx.navigateTo({
                        //                 url: "/pages/login/main"
                        //             })
                        //         }
                        //     }
                        // })
                    } else {
                        resolve(res.data);
                    }
                },
                fail: error => {
                    wx.showToast({
                        title: "请求失败",
                        icon: 'error'
                    })
                    reject();
                }
            })
        })
    },
    get(options = {}) {
        options['method'] = 'get';
        return this.request(options);
    },
    post(options = {}) {
        options['method'] = 'post';
        options['data'] = JSON.stringify(options['data']);
        return this.request(options);
    },
    put(options = {}) {
        options['method'] = 'put';
        return this.request(options);
    },
    delete(options = {}) {
        options['method'] = 'delete';
        return this.request(options);
    }
}

export default http